package com.ruoyi.web.controller.ctManage;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ruoyictmanage.domain.entity.*;
import com.ruoyi.ruoyictmanage.service.MPNService;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/ctManage")
public class ctManageConterller {

    private getCTDTO getctdto;

    private String mpnName;
    private String ie;
    private Integer line_id;
    private Integer state;
    private String timeStar;
    private String timeEnd;

    @Autowired
    private MPNService mpnService;

    @GetMapping("/getMPNlist")
    public PageInfo<MPN> MPNList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize){
        return mpnService.getMPNlist(pageNum,pageSize);
    }


    @GetMapping("/getLineList")
    public List<Line> lineList(){
        return mpnService.getLineList();
    }


    @GetMapping("/getUserIdUserNameByDeptId")
    public List<LinkUser> UserIdUserNameByDeptId(
    ){
        return mpnService.UserIdUserNameByDeptId(246L);
    }

    @GetMapping("/getUserLinkLine")
    public List<Integer> getUserLinkLine(
            @RequestParam(defaultValue = "1") Long userId
    ){
        return mpnService.getUserLinkLine(userId);
    }

    @GetMapping("/getUserLinkLineByLogin")
    public List<Line> getUserLinkLineByLogin(){
        Long userId = SecurityUtils.getLoginUser().getUserId();
        return mpnService.getLineListByLoginId(userId);
    }

    @PostMapping("/setUserLinkLine")
    public int setUserLinkLine(@Validated @RequestBody RequestDat requestDat
    ){
        return mpnService.setUserLinkLine(requestDat);
    }

    @PostMapping("/addMPN")
    public int addMPN(@Validated @RequestBody MPN mpn){
        System.err.println(mpn.toString());
        if (mpn.getMPN_id()>0){
            return mpnService.setMPN(mpn);
        }
        return mpnService.addMPN(mpn);
    }

    @PostMapping("/getCTTableByLineIdEnterDateMPNName")
    public PageInfo<MPNCTDTO> getCTTableByLineIdEnterDateMPNName(
            @Validated @RequestBody getCTDTO getCTDTO){
        getctdto=getCTDTO;
        return mpnService.getCTTableByLineIdEnterDateMPNName(getctdto,false);
    }

    @PostMapping("/getCTTableByLineIdEnterDateMPNNameHaveData")
    public PageInfo<MPNCTDTO> getCTTableByLineIdEnterDateMPNNameHaveData(
            @Validated @RequestBody getCTDTO getCTDTO){
        getctdto=getCTDTO;
        return mpnService.getCTTableByLineIdEnterDateMPNNameHaveData(getctdto);
    }

    @GetMapping("/getCTTableByCTId")
    public List<MPNCTDTO> getCTTableByCTId(
            @RequestParam(defaultValue = "1") Long ct_id){
        return mpnService.getCTTableByCTId(ct_id);
    }

    @PostMapping("/getCTTableDBByLineIdEnterDateMPNName")
    public List<MPNCTDTO> getCTTableDBByLineIdEnterDateMPNName(
            @Validated @RequestBody getCTDTO ctdto){
        return mpnService.getCTTableDBByLineIdEnterDateMPNName(ctdto);
    }

    @PutMapping("/setMpnState")
    public Long setMpnState(@RequestParam Long id,
                            @RequestParam(defaultValue = "1") int state){
        return mpnService.setMpnState(id,state);
//        return null;
    }

    @GetMapping("/selectMPNByQueryParams")
    public PageInfo<MPN> selectMPNByQueryParams(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "") String mpnName,
            @RequestParam(defaultValue = "") String ie,
            @RequestParam(defaultValue = "-1") Integer line_id,
            @RequestParam(defaultValue = "-1") Integer state,
            @RequestParam(defaultValue = "") String timeStar,
            @RequestParam(defaultValue = "") String timeEnd
    ){
        this.mpnName = mpnName;
        this.ie = ie;
        this.line_id = line_id;
        this.state = state;
        this.timeStar = timeStar;
        this.timeEnd = timeEnd;
        return mpnService.getMPNlistByQueryParams(pageNum,pageSize,mpnName,ie,line_id,state,timeStar,timeEnd);
    }

    @DeleteMapping("/del/{Id}")
    public int delSample(@PathVariable Long Id){
        return mpnService.delct(Id);
    }


    @PostMapping("/excel")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 1. 读取Excel数据
        List<MPN> dataList = EasyExcel.read(file.getInputStream())
                .head(MPN.class)
                .sheet()
                .doReadSync();


        // 2. 数据校验和处理
        if (dataList.isEmpty()) {
            return error("导入数据为空");
        }

//        // 3. 业务处理（示例：保存到数据库）
        mpnService.batchSave(dataList);

        return success("成功导入 " + dataList.size() + " 条数据");
    }

    @GetMapping("/template")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("数据导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. 创建空数据列表（仅表头）
        List<MPN> emptyList = Collections.emptyList();

        // 3. 导出模板
        EasyExcel.write(response.getOutputStream(), MPN.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(
                        createHeaderStyle(),  // 表头样式
                        new WriteCellStyle()  // 内容样式
                ))
                .sheet("导入模板")
                .doWrite(emptyList);
    }

    // 创建表头样式
    private WriteCellStyle createHeaderStyle() {
        WriteCellStyle style = new WriteCellStyle();
        WriteFont font = new WriteFont();
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        style.setWriteFont(font);
        return style;
    }

    @PostMapping("/setCTtable")
    public int setCTtable(@Validated @RequestBody CT ct){
        System.err.println(ct.toString());
        if (ct.getCT_id()>0){
            return mpnService.setUpdateCTtable(ct);
        }else {
            return mpnService.setAddCTtable(ct);
        }
    }

    @PostMapping("/exportCT")
    public void export(HttpServletResponse response) throws IOException {
        // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("CT表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        // 2. Get data

        List<MPNCTDTO> dataList = mpnService.getCTTableByLineIdEnterDateMPNName(getctdto, true).getList();


        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), MPNCTDTO.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {

                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("CT列表").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

    //导出MPN
    @PostMapping("/exportMpn")
    public void exportMpn(HttpServletResponse response) throws IOException {
        // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("MPN表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        // 2. Get data

        List<MPN> dataList = mpnService.getMPNlistByQueryParams(mpnName,ie,line_id,state,timeStar,timeEnd);


        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), MPN.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {

                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("mpn").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }


    @PostMapping("/ctexcel")
    public AjaxResult importctExcel(@RequestParam("file") MultipartFile file) throws IOException {
//        System.err.println(EasyExcel.read(file.getInputStream()));
        // 1. 读取Excel数据
        List<CT> dataList = EasyExcel.read(file.getInputStream())
                .head(CT.class)
                .sheet()
                .doReadSync();

        for (CT ct : dataList) {
            System.err.println(ct.toString());
        }

        dataList.forEach(CT::combineColumnsToList);

        // 2. 数据校验和处理
        if (dataList.isEmpty()) {
            return error("导入数据为空");
        }

//        // 3. 业务处理（示例：保存到数据库）
        mpnService.batchSaveCT(dataList);

        return success("成功导入 " + dataList.size() + " 条数据");
    }

    @GetMapping("/cttemplate")
    public void exportctTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("数据导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. 创建空数据列表（仅表头）
        List<CT> dataList = Collections.emptyList();
        // 预处理：将List拆分为列
        dataList.forEach(CT::splitListToColumns);

        // 3. 导出模板
        EasyExcel.write(response.getOutputStream(), CT.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(
                        createHeaderStyle(),  // 表头样式
                        new WriteCellStyle()  // 内容样式
                ))
                .sheet("导入模板")
                .doWrite(dataList);
    }

    @PutMapping("setBatchMpnState")
    public int setBatchMpnState(@RequestBody List<List<String>> multipleSelection){
        return mpnService.setBatchMpnState(multipleSelection);
    }

}
